package com.cinema.servlet.user;

import com.cinema.dao.UserDAO;
import com.cinema.entity.User;
import com.cinema.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录Servlet
 */
public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 显示登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        
        // 参数验证
        if (isEmpty(username) || isEmpty(password) || isEmpty(phone)) {
            request.setAttribute("error", "用户名、密码和手机号都不能为空");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        
        try {
            // 密码加密
            String encryptedPassword = PasswordUtil.encrypt(password);
            
            // 验证登录
            User user = userDAO.login(username, encryptedPassword);
            
            if (user != null) {
                // 验证手机号是否匹配
                if (!phone.equals(user.getPhone())) {
                    request.setAttribute("error", "手机号不匹配");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                    return;
                }
                
                // 登录成功，保存用户信息到session
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                session.setAttribute("userId", user.getId());
                session.setAttribute("username", user.getUsername());
                session.setAttribute("userRole", user.getRole());
                
                // 根据用户角色跳转
                if ("ADMIN".equals(user.getRole())) {
                    response.sendRedirect(request.getContextPath() + "/admin/movies");
                } else {
                    response.sendRedirect(request.getContextPath() + "/movies");
                }
            } else {
                // 登录失败，检查用户名是否存在
                User existUser = userDAO.findByUsername(username);
                if (existUser == null) {
                    // 用户名不存在，跳转到注册页面
                    request.setAttribute("message", "用户名不存在，请先注册");
                    request.setAttribute("username", username);
                    request.setAttribute("phone", phone);
                    request.getRequestDispatcher("/register.jsp").forward(request, response);
                } else {
                    // 密码错误，显示找回密码功能
                    request.setAttribute("error", "密码错误");
                    request.setAttribute("showForgotPassword", true);
                    request.setAttribute("username", username);
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "登录过程中发生错误，请稍后重试");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
    
    /**
     * 检查字符串是否为空
     */
    private boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
}
